package com.le.tester.book.concurrentchallenge.explicitlock13;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * createTime：2025-05-19 10:06
 * description：读写map
 */
public class ReadWriteMap<K, V> {
    private final Map<K, V> map;

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final Lock r = lock.readLock();

    private final Lock w = lock.writeLock();

    public ReadWriteMap(Map<K, V> map) {
        this.map = map;
    }

    public V put(K key, V value) {
        w.lock();
        try {
            return map.put(key, value);
        } finally {
            w.unlock();
        }
    }

    public V get(Object k) {
        r.lock();
        try {

//            编译器报警此处call get()，表示疑问
//            因为K的类型并不明确，使用object和泛型(K)的冲突，但是理论上是一致的
            return map.get(k);
        } finally {
            r.unlock();
        }
    }
}
